new Vue({
    el: '#app',
    data() {
        return {
            products: [
                // { name: '商品1', code: '001', price: 10.00, quantity: 1 },
                // { name: '商品2', code: '002', price: 20.00, quantity: 1 }
            ],
            activeName: '',
            selectedDiscount: 1,
            discountTitle: "添加优惠",
            discountOptions: [
                { label: "9.5折", value: 0.95, selected: false },
                { label: "9折", value: 0.9, selected: false },
                { label: "8.5折", value: 0.85, selected: false },
                { label: "8折", value: 0.8, selected: false },
                { label: "7.5折", value: 0.75, selected: false },
                { label: "7折", value: 0.7, selected: false },
            ],
            displayNumber: '',
            showProducts: false,
            orders: [
                // {
                // items: [
                // { name: '商品A', quantity: 2, price: 50 },
                // { name: '商品B', quantity: 1, price: 30 }
                //     ]
                // },
                // {
                //     items: [
                //         { name: '商品C', quantity: 2, price: 50 },
                //     ]
                // },
                // {
                //     items: [
                //         { name: '商品A', quantity: 2, price: 50 },
                //         { name: '商品B', quantity: 1, price: 30 }
                //     ]
                // },
                // {
                //     items: [
                //         { name: '商品A', quantity: 2, price: 50 },
                //         { name: '商品B', quantity: 1, price: 30 }
                //     ]
                // },
            ],
            isPopupVisible: false,
            showQrcode:false,
            pay: [
                { icon: '../../admin/images/money.png', text: '现金', content: 'Content for Option 1', selected: false },
                { icon: '../../admin/images/Alipay.png', text: '支付宝', content: 'Content for Option 2', selected: false },
                { icon: '../../admin/images/Wechat.png', text: '微信', content: 'Content for Option 3', selected: false },
                { icon: '../../admin/images/BankCards.png', text: '银行卡', content: 'Content for Option 4', selected: false }
            ],
            searchQuery: '',
            searchVip: '',
            searchResults: [],
            form: {
                Article_Name: '',
                sort: '',
                Category_SerialNumber: '',
                page: 1,			//页数
                limit: 10,			//每页数据条数
                Enterprise_Info_SerialNumber: $.cookie("enterprise"),
            },
            total1: 0,
            // total2: 0,
            countdownDuration: 15 * 60 * 1000, // 15 minutes in milliseconds
            countdownIntervals: [],
            money: '2252.00',
            name: '李华',
            vipNumber: '111222333',
            radioValue: false,
            selectedOrder: null,
            totalPrice: 0,
            totalflag: true,
            displayTotal: 0,
            selectedOption: 'barcode',
            Sales_Order_SerialNumber: '',
        }

    },
    mounted() {
        this.getMove();
    },
    computed: {
        totalQuantity() {
            return this.products.reduce((total, product) => total + product.quantity, 0);
        },
        totalPrice1() {
            return this.products.reduce((total, product) => total + (product.Sales_Unit_Price * product.quantity), 0).toFixed(2);
        },
        discount() {
            return (this.totalPrice1 * (1 - this.selectedDiscount)).toFixed(2);
        },
        total() {
            // if (this.selectedOrder) {
            //     let totalPrice = this.selectedOrder.items.reduce((acc, item) => acc + (item.Sales_Unit_Price * item.quantity), 0);
            //     return totalPrice.toFixed(2);
            // } else {
            // 没有选中的挂单，显示商品列表的实收价格
            //     let totalPayable = this.totalPrice - this.discount;
            //     return totalPayable.toFixed(2);
            // }
            return (this.totalPrice1 - this.discount).toFixed(2);
        },
        // 添加计算属性判断是否余额大于0
        isBalancePositive() {
            return this.money > 0;
        }
    },
    methods: {
        getMove() {
            var popup = document.querySelector("#popup")
            var title = document.querySelector('#title')
            title.addEventListener('mousedown', function (e) {
                var x = e.clientX - popup.offsetLeft;
                var y = e.clientY - popup.offsetTop;
                document.addEventListener('mousemove', move)
                function move(e) {
                    popup.style.left = e.clientX - x + 'px';
                    popup.style.top = e.clientY - y + 'px';
                    window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
                }
                // 选项框取消移动
                title.addEventListener('mouseup', function () {
                    document.removeEventListener('mousemove', move);
                })
            })

            title.addEventListener('selectstart', function (e) {
                e.preventDefault();
            })
        },
        selectItem(selectedItem) {
            this.pay.forEach(item => {
                item.selected = (item === selectedItem);
            });
            console.log('item.text', selectedItem.text);
        },
        incrementQuantity(index) {
            this.products[index].quantity++;
        },
        decrementQuantity(index) {
            if (this.products[index].quantity > 1) {
                this.products[index].quantity--;
            }
        },
        formatPrice(row, column, cellValue) {
            return '¥ ' + cellValue.toFixed(2);
        },
        deleteProduct(row) {
            this.products.splice(this.products.indexOf(row), 1);
        },
        clearProducts() {
            this.products = [];
        },
        handleChange(row) {
            console.log(row.quantity);
        },
        toggleDiscountStatus() {
            this.discountTitle = this.discountTitle === "添加优惠" ? "取消优惠" : "添加优惠";
            if (this.discountTitle === "添加优惠") {
                this.selectedDiscount = 1;
            }
        },
        updateDiscount(value) {
            this.selectedDiscount = value;
        },
        showCalculator() {
            document.getElementById("normalContent").style.display = "none";
            document.getElementById("calculatorContent").style.display = "block";
        },
        hideCalculator() {
            document.getElementById("normalContent").style.display = "block";
            document.getElementById("calculatorContent").style.display = "none";
        },
        appendToDisplay(value) {
            if (this.displayNumber === '请输入金额') {
                this.displayNumber = value.toString();
            } else {
                this.displayNumber += value.toString();
            }
        },
        deleteLastCharacter() {
            this.displayNumber = this.displayNumber.slice(0, -1);
            if (this.displayNumber === '') {
                this.displayNumber = '0';
            }
        },
        // removeOrder(index) {
        //     this.orders.splice(index, 1);
        // },
        getTotalItems(order) {
            let total = 0;
            order.items.forEach(item => {
                total += item.quantity;
            });
            return total;
        },
        // clearOrders() {
        //     this.orders = [];
        // },
        goBack() {
            this.showProducts = false;
        },
        getTotalPrice(order) {
            let totalPrice = order.items.reduce((acc, item) => acc + (item.Sales_Unit_Price * item.quantity), 0);
            return totalPrice;
        },
        showPopup(order) {
            this.selectedOrder = order;
            this.isPopupVisible = true;
        },
        showPopupWithCurrentOrder(orderIndex) {
            // this.totalflag = !!type;
            if (orderIndex !== null) {
                // 如果是点击"合计"，根据订单索引计算并设置显示的总金额
                this.displayTotal = this.getTotalPrice(this.orders[orderIndex]);
            } else {
                // 如果是点击"立即结算"，显示total
                this.displayTotal = this.total;
            }
            this.isPopupVisible = true;
        },
        hidePopup() {
            this.isPopupVisible = false;
            // this.showQrcode = false;
            console.log('this.isPopupVisible', this.isPopupVisible);
        },
        showContent(index) {
            this.selected = index;
        },
        searchProducts() {
            if (this.searchQuery.trim() !== '') {
                if (this.selectedOption === 'barcode') {
                    console.log('this.selectedOption', this.selectedOption);
                    this.form.Article_Name = this.searchQuery;
                    this.fuzzySearchProducts(this.form); // 条形码的搜索接口
                } else if (this.selectedOption === 'size') {
                    console.log('this.selectedOption1', this.selectedOption);
                    // 货品尺码的搜索接口
                    this.searchBySize(this.searchQuery);
                }
            } else {
                this.searchResults = [];
            }
        },
        changeSearchType() {
            this.searchQuery = ''; // 切换搜索类型时，清空搜索内容
        },
        searchVip() {

        },
        fuzzySearchProducts(data) {
            let _this = this
            $.ajax({
                url: DomainName + '/getGroupGoodsAll?token=' + $.cookie('token'),
                type: 'POST',
                data,
                success: function (res) {
                    console.log('搜索', res);
                    if (res.Status == 'success') {
                        _this.searchResults = res.tableData
                        _this.total1 = parseInt(res.limit);
                        console.log('_this.searchResults', _this.searchResults);
                    }
                },
                complete: function (XMLHttpRequest) {
                    _this.loading = false
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                }
            })
        },
        Payfor() {
            let _this = this;
            if (_this.products.length > 0) {
                _this.loading = true
                var Check = [];
                let sales_order_detail = [];
                this.products.forEach(item => {
                    sales_order_detail.push({
                        Sales_Order_Detail_SerialNumber: '',
                        Sales_Order_SerialNumber: '',
                        Sales_Unit_Price_Stock_SerialNumber: item.Sales_Unit_Price_Stock_SerialNumber,
                        Article_SerialNumber: item.Article_SerialNumber,
                        Article_Specifications_SerialNumber: item.Article_Specifications_SerialNumber,
                        Sign: item.Sign,
                        Quantity: item.quantity,
                        Unit_Price: item.Unit_Price,
                        Sales_Unit_Price: item.Sales_Unit_Price,
                        Amount: accMul(item.Sales_Unit_Price, item.quantity),
                        Receive_Type: 0,
                        Refund_Type: 0,
                        Enterprise_Info_SerialNumber: $.cookie('enterprise'),
                    })
                    const checkobj = {}
                    checkobj.Sales_Unit_Price_Stock_SerialNumber = item.Sales_Unit_Price_Stock_SerialNumber
                    checkobj.Quantity = item.quantity
                    Check.push(checkobj)
                })
                let sales_order = {
                    Sales_Order_SerialNumber: '',
                    Store_SerialNumber: "",
                    Sales_Address: '',
                    Sales_Contacts: '',
                    Sales_Phone: '',
                    Sales_Message: '',
                    Sales_Date: getYMDHMSDate(),
                    Open_ID: "",
                    App_ID: "wx9b74a42a123612c9",
                    Sales_Amount: this.displayTotal,
                    Collection_Amount: 0,
                    Delivery_Amount: 0,
                    Receive_Type: 0,
                    Refund_Type: 0,
                    Enterprise_Info_SerialNumber: $.cookie("enterprise"),
                    Children: {
                        sales_order_detail,
                    },
                }
                $.ajax({
                    url: DomainName + '/WeChatsetSalesOrderAction?token=' + $.cookie('token'),
                    type: 'POST',
                    data: {
                        Type: 1,
                        Check: JSON.stringify(Check),
                        Data: JSON.stringify({ sales_order: [sales_order] })
                    },
                    success: function (res) {
                        console.log('支付', res);
                        if (res.Status == 'success') {
                            // _this.Sales_Order_SerialNumber = res.Data
                            _this.Pay(res.Data);
                            console.log('_this.searchResults', _this.searchResults);
                        }
                    },
                    complete: function (XMLHttpRequest) {
                        _this.loading = false
                        if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                        }
                    }
                })
            }
        },
        Pay(Sales_Order_SerialNumber) {
            let _this = this;
            let selectedPay = this.pay.find(item => item.selected);

            if (selectedPay) {
                let selectedText = selectedPay.text;
                let Collection_Type;

                if (selectedText === '微信') {
                    Collection_Type = "微信支付-PC";
                } else if (selectedText === '储值支付') {
                    Collection_Type = "储值账户-PC";
                } else if (selectedText === '支付宝') {
                    Collection_Type = "支付宝支付-PC";
                }

                console.log('Collection_Type', Collection_Type);

                $.ajax({
                    url: DomainName + '/WXWeChatDefrayAction?token=' + $.cookie('token'),
                    type: 'POST',
                    data: {
                        Sales_Order_SerialNumber,
                        Collection_Type
                    },
                    success: function (res) {
                        console.log('支付1', res);
                        // if (res.Status == 'success') {
                        //     _this.searchResults = res.tableData
                        //     _this.total1 = parseInt(res.limit);
                        //     console.log('_this.searchResults', _this.searchResults);
                        // }
                        if (Collection_Type == '微信支付-PC' && res.result_msg == 'SUCCESS') {
                            // 显示二维码
                            // let qrcode = new QRCode(document.getElementById("qrcode"), {
                            //     text: res.code_url,
                            //     width: 200,
                            //     height: 200
                            // });
                            let picwidth = 200;
                            let picheight = 200; 
                            let qrcodeDivId = 'qrcode';
                            $('<div>').attr('id', qrcodeDivId).appendTo('body');
                            $(`#${qrcodeDivId}`).qrcode({
                                // render: table,
                                width: picwidth, //宽度
                                height: picheight,//高度
                                text: res.code_url,//内容
                                typeNumber: -1,//计算模
                                correctLevel: 2,//二维码纠错级别
                                background: "#ffffff",//背景额色
                                foreground: "#898888"//二维码额色
                            })
                            _this.hidePopup();
                            _this.showQrcode = true;
                            console.log('qrcode', qrcodeDivId);
                        }else if(Collection_Type == '支付宝支付-PC' && res.Status == 'success'){
                            console.log('支付宝支付',res);
                            sessionStorage.setItem("body", res.Data)
                            window.location.href = './Alipay.html' 
                        }
                    },
                    complete: function (XMLHttpRequest) {
                        _this.loading = false;
                        if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                        }
                    }
                });
            } else {
                console.error('No payment method selected.');
            }
        },
        searchBySize(data) {
            console.log(data);
            // let _this = this
            // $.ajax({
            //     url: DomainName + '/getGroupGoodsAll?token=' + $.cookie('token'),
            //     type: 'POST',
            //     data,
            //     success: function (res) {
            //         console.log('搜索', res);
            //         if (res.Status == 'success') {
            //             _this.searchResults = res.tableData
            //             _this.total1 = parseInt(res.limit);
            //             console.log('_this.searchResults', _this.searchResults);
            //         }
            //     },
            //     complete: function (XMLHttpRequest) {
            //         _this.loading = false
            //         if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            //             window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            //         }
            //     }
            // })
        },
        handleSizeChange(val) {
            this.form.page = 1;
            this.form.limit = val;
            this.getList(this.form)
        },
        handleCurrentChange(val) {
            this.form.page = val;
            this.getList(this.form)
        },
        // 添加商品到购物车
        addProductToCart(product) {
            // 检查商品是否已存在于购物车中
            const existingProductIndex = this.products.findIndex(p => p.Article_Specifications_SerialNumber === product.Article_Specifications_SerialNumber);
            if (existingProductIndex !== -1) {
                // 如果商品已存在，则增加商品数量
                this.products[existingProductIndex].quantity++;
            } else {
                // 如果商品不存在，则添加新商品到购物车中
                this.products.push({ ...product, quantity: 1 });
            }
            this.backToSearchList();
        },
        // 返回商品列表
        backToSearchList() {
            this.searchQuery = '';
        },
        addToOrders() {

            if (this.products.length <= 0) {
                const confirmation = confirm('当前没商品，无法挂单！！！');
            } else {
                if (this.orders.length > 0) {
                    const confirmation = confirm('确定要将当前商品列表加入挂单吗？');
                    if (!confirmation) return;
                }
                const creationTime = Date.now(); // 记录订单创建时间
                this.orders.push({
                    items: this.products,
                    creationTime: creationTime, // 添加创建时间到订单对象中
                });
                this.products = [];
                this.backToSearchList();
                this.showProducts = false;
                // this.startCountdown(this.orders.length - 1);
                console.log(this.showProducts);
                console.log(JSON.stringify(this.orders));
                confirm('挂单成功！！！！')
                // this.showProducts = true;
            }
        },
        toggleShowProducts() {
            console.log(this.showProducts);
            if (this.showProducts == false) {
                this.showProducts = true;
            } else {
                console.log("KK");
                console.log(this.showProducts);
            }
        },
        // startCountdown(index) {
        //     const order = this.orders[index];
        //     const intervalId = setInterval(() => {
        //         const now = Date.now();
        //         const countdownEnd = order.creationTime + this.countdownDuration;
        //         if (now >= countdownEnd) {
        //             this.removeOrder(index); // 如果订单超时，则删除订单
        //         } else {
        //             const remainingTime = countdownEnd - now;
        //             const minutes = Math.floor(remainingTime / (1000 * 60));
        //             const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
        //             const formattedTime = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
        //             this.$set(this.orders[index], 'countdown', formattedTime); // 更新订单倒计时
        //         }
        //     }, 1000);
        //     this.countdownIntervals[index] = intervalId; // 更新指定订单的倒计时索引
        // },
        clearOrders() {
            this.orders = [];
            this.countdownIntervals.forEach(interval => clearInterval(interval));
        },
        // getOrderCountdown(index) {
        //     const order = this.orders[index];
        //     const creationTime = order.creationTime;
        //     const countdownEnd = creationTime + this.countdownDuration;
        //     const now = Date.now();
        //     if (now >= countdownEnd) {
        //         this.removeOrder(index);
        //         return '已过期';
        //     }
        //     const remainingTime = countdownEnd - now;
        //     const minutes = Math.floor(remainingTime / (1000 * 60));
        //     const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
        //     return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
        // },
        removeOrder(index) {
            // 删除指定订单并清除其倒计时
            clearInterval(this.countdownIntervals[index]);
            this.orders.splice(index, 1);
            delete this.countdownIntervals[index]; // 从倒计时数组中移除对应项
            // 调整countdownIntervals数组，确保后面的订单倒计时索引与订单索引同步
            this.countdownIntervals = this.countdownIntervals.filter((id) => id !== undefined);
        },
    }
});